import json, struct, sys, socket

class ciclient:
    def __init__(self, strHost, intPort):
        self.Host = strHost
        self.Port = intPort
        self.sock = None
        self._connect();
    def _connect(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(0.1)
        try:
            self.sock.connect((self.Host, self.Port));
            self.sock.settimeout(1)
            return True
        except socket.timeout:
            print "connect TimeOut"
            return False
        except socket.error, arg:
            (errno, err_msg) = arg
            print "Connect server failed: %s, errno=%d" % (err_msg, errno)
            return False

    def _check_connect(self):
        rstr="a"
        try:
            self.sock.setblocking(False)
            rstr= self.sock.recv(1)
            if rstr == "" or len(rstr) == 1:
                print "remote server closed or left data len[%u]" % (len(rstr),)
                self.sock.close()
                return self._connect()
        except socket.error, e:
            self.sock.settimeout(1)
            print 'rstr[%s] len[%u] socket:%s' % (rstr, len(rstr), e,)
            return True

    def commit(self, log_id, queue_name, operation, dict4commit):
        FMT_XHEAD = "I16sIII"
        dd = {}
        dd['__QUEUE_NAME__']      = queue_name
        dd['__OPERATION__']       = operation
        dd['__OPERATION_BODY__']  = dict4commit
        jsonstr = json.dumps(dd)
        sbuf = struct.pack(FMT_XHEAD, log_id, "pyclient", 0, 0, len(jsonstr))
        sbuf += jsonstr
        if self._check_connect():
            try:
                self.sock.send(sbuf)
            except socket.error, arg:
                print "error message [%s]" % (arg, )
                return False
            rbuf = self.sock.recv(32)
            log_id, srvname, version, reserved, detail_len = struct.unpack(FMT_XHEAD, rbuf)
            print "logid[%u] srvname[%s] version[%u] reserved[%u] detail_len[%u]" % (log_id, \
                    srvname, version, reserved, detail_len)
            return reserved == 0
        else:
            return False

if __name__ == "__main__":
    host = ["111.111.111.111", "127.0.0.1"]
    mycc = ciclient(host[1], 1983)
    for x in range(int(sys.argv[1])):
        dd={}
        dd["vid"] = x + 1
        dd["title"] = "beauty girls [%08u]" % (x+1,)
        mycc.commit(x, "video", "ADD", dd)
